package com.coszero.utils.utils

import android.app.Activity
import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.util.Log
import java.io.File
import java.net.URLDecoder

/**
 * Desc： 用于打开系统的app
 *
 *
 * Author： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/7/27 16:30
 * @version 1
 */
object OpenSystemAppUtils {
    /**
     * 打开系统浏览器
     *
     * @param url "https://xxx"
     * @link 原文：https://blog.csdn.net/Aminy123/article/details/81510354
     */
    fun openSystemBrowser(activity: Activity, url: String?) {
        var url: String? = url
        if (url!!.contains("%3A")) {
            //异常字符转换
            url = URLDecoder.decode(url)
        }
        if (!url!!.startsWith("http") && !url.startsWith("https")) {
            //如来链接地址不是http或者https开头，则加上
            url = "https://" + url
        }
        try {
            //###8.0以下
            val intent: Intent = Intent()
            intent.setAction(Intent.ACTION_VIEW)
            val content_url: Uri = Uri.parse(url) //要跳转的网页
            intent.setData(content_url)
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity")
            } else {
                //###8.0
                intent.setClassName(
                    "org.chromium.webview_shell",
                    "org.chromium.webview_shell.WebViewBrowserActivity"
                )
            }
            activity.startActivity(intent)
        } catch (e: Exception) {
            LogX.e("OpenSystemAppUtils.openSystemBrowser", "跳转系统浏览器异常")
            e.printStackTrace()
        } finally {
            try {
                //先尝试跳转系统浏览器，实在跳转不了就让用户自己选
                val intent1: Intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                activity.startActivity(intent1)
            } catch (e: Exception) {
                LogX.e("OpenSystemAppUtils.openSystemBrowser", "跳转浏览器链接地址异常")
                e.printStackTrace()
            }
        }
    }

    /**
     * 打开系统相册
     *
     * @param activity
     * @param requestCode 请求码
     */
    fun openSystemImage(activity: Activity, requestCode: Int) {
        val intent: Intent = Intent()
        intent.setAction(Intent.ACTION_PICK)
        intent.setType("image/*")
        activity.startActivityForResult(intent, 2)
    }

    /**
     * 打开安装器
     *
     * @param context
     * @param downloadApkId
     * @param apkPath
     */
    fun openInstallApk(context: Context, downloadApkId: Long, apkPath: String) {
        val dManager: DownloadManager =
            context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        val install: Intent = Intent(Intent.ACTION_VIEW)
        val downloadFileUri: Uri? = dManager.getUriForDownloadedFile(downloadApkId)
        if (downloadFileUri != null) {
            Log.e("DownloadManager", downloadFileUri.toString())
            install.setDataAndType(
                Uri.parse("file://" + apkPath),
                "application/vnd.android.package-archive"
            )
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(install)
        } else {
            Log.e("DownloadManager", "download error")
        }
    }

    /**
     * 打开文件管理器
     *
     *
     * onActivityResult(int requestCode, int resultCode, Intent data) {
     * if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
     * Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
     * String[] proj = {MediaStore.Images.Media.DATA};
     * Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
     * int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
     * actualimagecursor.moveToFirst();
     * String img_path = actualimagecursor.getString(actual_image_column_index);
     * File file = new File(img_path);
     * Toast.makeText(MainActivity.this, file.toString(), Toast.LENGTH_SHORT).show();
     * }
     * }
     */
    fun openFileManager(activity: Activity, file: File?) {
        val intent: Intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.setType("*/*") //设置类型，我这里是任意类型，任意后缀的可以这样写。
        //          intent.setType(“image/*”); //选择图片
//          intent.setType(“audio/*”); //选择音频
//          intent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
//          intent.setType(“video/*;image/*”);//同时选择视频和图片
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        activity.startActivityForResult(intent, 1)
    }
}
